package com.xitang.system.controller;

import com.qiniu.util.Auth;
import com.xitang.common.dto.ResultVO;
import com.xitang.system.dto.QiniuToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@Api(tags = "基础系统功能-系统")
@RestController
public class BasicSystemController extends BaseSystemController {
    @Value("${qiniu.ak}")
    private String accessKey;

    @Value("${qiniu.sk}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domain}")
    private String domain;

    private final static String templatePath = "template";

    private final static String productFileName = "分类产品材料导入表.xlsm";

    @ApiOperation(value = "获取七牛云token", notes = "获取七牛云token，用于上传文件")
    @GetMapping("/upload/token")
    public ResultVO<QiniuToken> getUploadToken(@RequestParam String suffix) throws Exception {
        // 是否可以上传的图片格式
        boolean flag = false;
        String[] imgTypes = new String[]{"jpg", "jpeg", "bmp", "gif", "png"};
        for (String fileSuffix : imgTypes) {
            if (suffix.substring(suffix.lastIndexOf(".") + 1).equalsIgnoreCase(fileSuffix)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            throw new Exception("图片：" + suffix + " 上传格式不对！");
        }

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        QiniuToken token = new QiniuToken();
        token.setToken(upToken);
        token.setDomain(domain);

        String randomFileName = UUID.randomUUID().toString() + suffix;
        token.setImgUrl(randomFileName);
        return ResultVO.success(token);
    }

    @GetMapping("/template/download")
    public String download(HttpServletResponse response) throws Exception {
        String path = templatePath + "/" + productFileName;
        try (OutputStream outputStream = response.getOutputStream()) {
            ClassPathResource classPathResource = new ClassPathResource(path);
            if (!classPathResource.exists()) {
                throw new Exception("模板不存在");
            }
            File file = classPathResource.getFile();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(productFileName, "utf-8"));

            Files.copy(Paths.get(file.getPath()), outputStream);
        } catch (Exception e) {
            throw new Exception("模板下载失败");
        }
        return null;
    }
}
